package com.fowo.api.service.handleWork;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.entity.LoanMonthlyBalance;
import com.fowo.api.entity.LoanNowBalance;
import com.fowo.api.entity.StockIn;
import com.fowo.api.mapper.LoanNowBalanceMapper;
import com.fowo.api.mapper.StockInMapper;
import com.fowo.api.model.loan.monthly.balance.LoanMonthlyBalanceVo;
import com.fowo.api.model.loan.now.balance.LoanNowBalanceVo;
import com.fowo.api.model.purchase.order.PurchaseOrderCashOutAction;
import com.fowo.api.model.purchase.order.PurchaseOrderVo;
import com.fowo.api.model.purchase.order.product.PurchaseOrderProductItemVo;
import com.fowo.api.service.LoanMonthlyBalanceService;
import com.fowo.api.service.LoanNowBalanceService;
import com.fowo.api.service.PurchaseOrderService;
import com.fowo.api.service.StockInService;
import com.fowo.api.service.impl.LoanMonthlyBalanceServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Component
public class PurchaseOrderCashOut implements PurchaseOrderCashOutAction {

    @Resource
    private PurchaseOrderService purchaseOrderService;
    @Resource
    private LoanNowBalanceService loanNowBalanceService;
    @Resource
    private LoanNowBalanceMapper loanNowBalanceMapper;
    @Resource
    private LoanMonthlyBalanceServiceImpl loanMonthlyBalanceService;
    @Resource
    private StockInMapper stockInMapper;

    @Override
    public void run(Long id) throws Exception {
        PurchaseOrderVo purchaseOrderVo = purchaseOrderService.getVoById(id);
        String settlementMethod = purchaseOrderVo.getSettlementMethod();
        Assert.notNull(settlementMethod,"请选择结算方式");
        switch (settlementMethod){
            case "JS01": //现结
                insertLoanNowBalance(purchaseOrderVo);
                break;
            case "JS02": //月结
                insertLoanMonthlyBalance(purchaseOrderVo);
                break;
            default:
                throw new Exception("结算方式错误");
        }
    }

    /**
     * 添加贷款现结
     * @param purchaseOrderVo
     * @throws Exception
     */
    public void insertLoanNowBalance(PurchaseOrderVo purchaseOrderVo) throws Exception {
        LoanNowBalance loanNowBalance = loanNowBalanceMapper.selectOne(Wrappers.lambdaQuery(LoanNowBalance.class)
                .eq(LoanNowBalance::getPurchaseOrderCode,purchaseOrderVo.getPurchaseOrderCode()));
        if(null != loanNowBalance){
            throw new Exception("该采购单已经请款，请勿重复请款");
        }

        LoanNowBalanceVo loanNowBalanceVo = new LoanNowBalanceVo();
        loanNowBalanceVo.setSupplierName(purchaseOrderVo.getSupplierId());
        loanNowBalanceVo.setPurchaseOrderCode(purchaseOrderVo.getPurchaseOrderCode());
        loanNowBalanceVo.setApplicationDep(purchaseOrderVo.getApplicationDep());
        loanNowBalanceVo.setDescribe(purchaseOrderVo.getSettlementDescribe());
        loanNowBalanceVo.setBudgetRatio(purchaseOrderVo.getAdvanceRatio());
        loanNowBalanceVo.setPayType(purchaseOrderVo.getPaymentMethod());
//        loanNowBalanceVo.setUserName();
//        loanNowBalanceVo.setBankOfDeposit();
//        loanNowBalanceVo.setAccount();
        loanNowBalanceVo.setCurrency(purchaseOrderVo.getPurchaseCurrency());
        loanNowBalanceVo.setOptUid(purchaseOrderVo.getOptUid());
        loanNowBalanceVo.setRemarks(purchaseOrderVo.getRemarks());

        BigDecimal salesReturnMoney = new BigDecimal(0.0);
        Integer purchaseQuantity = 0;
        Integer quantityReceived = 0;
        BigDecimal totalPrice = new BigDecimal(0.0);
        BigDecimal aogMoney = new BigDecimal(0.0);
        for(PurchaseOrderProductItemVo PurchaseOrderProduct : purchaseOrderVo.getPurchaseOrde()){
            purchaseQuantity += PurchaseOrderProduct.getApplicationNum();
            int quantity = PurchaseOrderProduct.getQuantityReceived() == null ? 0 : PurchaseOrderProduct.getQuantityReceived();
            quantityReceived += quantity;
            totalPrice = totalPrice.add(PurchaseOrderProduct.getTotalPrice());
            aogMoney = aogMoney.add(PurchaseOrderProduct.getUnitPrice().multiply(new BigDecimal(quantity)));
            salesReturnMoney = PurchaseOrderProduct.getQuantityReturn() == null?
                    new BigDecimal(0.00):
                    salesReturnMoney
                            .add(PurchaseOrderProduct.getUnitPrice()
                                    .multiply(new BigDecimal(PurchaseOrderProduct.getQuantityReturn()))
                            );
        }
        loanNowBalanceVo.setPurchaseQuantity(purchaseQuantity);
        loanNowBalanceVo.setQuantityReceived(quantityReceived);
        loanNowBalanceVo.setPurchaseMoney(totalPrice);
        loanNowBalanceVo.setAogMoney(aogMoney);
        loanNowBalanceVo.setAmountPayable(totalPrice.subtract(salesReturnMoney));
        loanNowBalanceVo.setSalesReturnMoney(salesReturnMoney);
        loanNowBalanceVo.setActuallyPaid(new BigDecimal(0.0));
        loanNowBalanceVo.setUnpaidMoney(totalPrice.subtract(salesReturnMoney));
        loanNowBalanceVo.setInApplication(new BigDecimal(0.0));
        loanNowBalanceVo.setNotApply(totalPrice.subtract(salesReturnMoney));
        loanNowBalanceVo.setDiscountAmount(new BigDecimal(0.0));
        loanNowBalanceVo.setGoodsPrice(totalPrice);
        loanNowBalanceVo.setShippingPrice(purchaseOrderVo.getShippingPrice());
        loanNowBalanceVo.setOtherCurrency(purchaseOrderVo.getOtherCurrency());
        loanNowBalanceService.create(loanNowBalanceVo);
    }

    /**
     * 添加贷款月结
     * @param purchaseOrderVo
     * @throws Exception
     */
    public void insertLoanMonthlyBalance(PurchaseOrderVo purchaseOrderVo) throws Exception {
        LoanMonthlyBalance loanMonthlyBalance = loanMonthlyBalanceService.getOne(Wrappers.lambdaQuery(LoanMonthlyBalance.class)
                .eq(LoanMonthlyBalance::getPurchaseOrderCode,purchaseOrderVo.getPurchaseOrderCode()));
        if(null != loanMonthlyBalance){
            throw new Exception("该采购单已经请款，请勿重复请款");
        }

        LoanMonthlyBalanceVo loanMonthlyBalanceVo = new LoanMonthlyBalanceVo();
        loanMonthlyBalanceVo.setSupplierName(purchaseOrderVo.getSupplierId());
        loanMonthlyBalanceVo.setDescribe(purchaseOrderVo.getSettlementDescribe());
        loanMonthlyBalanceVo.setPurchaseOrderCode(purchaseOrderVo.getPurchaseOrderCode());
        loanMonthlyBalanceVo.setApplicationDep(purchaseOrderVo.getApplicationDep());
        loanMonthlyBalanceVo.setWid(purchaseOrderVo.getWid());
//        loanMonthlyBalanceVo.setClosingPeriod();
//        loanMonthlyBalanceVo.setDueDate();
        loanMonthlyBalanceVo.setBudgetRatio(purchaseOrderVo.getAdvanceRatio());
        loanMonthlyBalanceVo.setPayType(purchaseOrderVo.getPaymentMethod());
//        loanMonthlyBalanceVo.setUserName();
//        loanMonthlyBalanceVo.setBankOfDeposit();
//        loanMonthlyBalanceVo.setAccount();
        loanMonthlyBalanceVo.setCurrency(purchaseOrderVo.getPurchaseCurrency());
        loanMonthlyBalanceVo.setOptUid(purchaseOrderVo.getOptUid());

        List<StockIn> stockInList = stockInMapper.selectList(Wrappers.lambdaQuery(StockIn.class)
                .eq(StockIn::getAssociatedPo,purchaseOrderVo.getPurchaseOrderCode()));
        if(CollectionUtils.isNotEmpty(stockInList)){
            loanMonthlyBalanceVo.setOrderSn(stockInList.get(0).getOrderSn());
            loanMonthlyBalanceVo.setWarehousingDate(stockInList.get(0).getWarehousingDate());
            loanMonthlyBalanceVo.setTotalNum(stockInList.stream().mapToInt(in -> Integer.valueOf(in.getTotalNum())).sum());
            loanMonthlyBalanceVo.setStockinUid(stockInList.get(0).getCreateUser());
        }

        Integer purchaseQuantity = 0;
        Integer quantityReceived = 0;
        BigDecimal purchaseMoney = new BigDecimal(0.0);
        BigDecimal aogMoney = new BigDecimal(0.0);
        BigDecimal salesReturnMoney = new BigDecimal(0.0);
        for(PurchaseOrderProductItemVo PurchaseOrderProduct : purchaseOrderVo.getPurchaseOrde()){
            purchaseQuantity += PurchaseOrderProduct.getApplicationNum();
            quantityReceived += PurchaseOrderProduct.getQuantityReceived();
            purchaseMoney = purchaseMoney.add(PurchaseOrderProduct.getTotalPrice());
            //退货
            salesReturnMoney = salesReturnMoney.add(
                    PurchaseOrderProduct.getQuantityReturn() == null?
                    new BigDecimal(0.00):
                    PurchaseOrderProduct.getUnitPrice().multiply(new BigDecimal(PurchaseOrderProduct.getQuantityReturn()))
            );
            //到货
            aogMoney = aogMoney.add(
                    PurchaseOrderProduct.getQuantityReceived() == null?
                    new BigDecimal(0.00):
                    PurchaseOrderProduct.getUnitPrice().multiply(new BigDecimal(PurchaseOrderProduct.getQuantityReceived()))
            );
        }
        loanMonthlyBalanceVo.setPurchaseQuantity(purchaseQuantity);
        loanMonthlyBalanceVo.setPurchaseMoney(purchaseMoney);
        loanMonthlyBalanceVo.setQuantityReceived(quantityReceived);
        loanMonthlyBalanceVo.setAogMoney(aogMoney);
        loanMonthlyBalanceVo.setSalesReturnMoney(salesReturnMoney);
        loanMonthlyBalanceVo.setGoodsPrice(aogMoney);
        loanMonthlyBalanceVo.setShippingPrice(purchaseOrderVo.getShippingPrice());
        loanMonthlyBalanceVo.setOtherCurrency(purchaseOrderVo.getOtherCurrency());
        BigDecimal prepay = purchaseOrderVo.getAdvanceRatio() == null?
                new BigDecimal(0.00):
                purchaseMoney.multiply(purchaseOrderVo.getAdvanceRatio().multiply(new BigDecimal(0.01)));
        loanMonthlyBalanceVo.setNotApply(purchaseMoney.subtract(prepay));
        loanMonthlyBalanceService.create(loanMonthlyBalanceVo);
    }
}
